package dao

import (
	"context"
	"inventory/pkg/ecode"
	"time"

	"inventory/internal/model"
)

// FindScheduleOrders 获取仓库下调拨单列表
func (d *Dao) FindScheduleOrders(ctx context.Context, sgID, status, inWarehouseID, outWarehouseID uint32,
	startDate, endDate time.Time, pageNo, pageSize int, queryOrderNumber string) (total int64, orders []*model.ScheduleOrder, err error) {
	db := d.TransContext(ctx).Model(&model.ScheduleOrder{}).Where(
		"sg_id = ? and apply_time between ? and ? ", sgID, startDate, endDate.Add(time.Hour*24-time.Second))
	if queryOrderNumber != "" {
		if len(queryOrderNumber) < 4 {
			err = ecode.BadRequest("单号模糊搜索至少需要4位数字")
		}
		db = db.Where("order_number like ?", "%"+queryOrderNumber+"%")
	}
	if inWarehouseID != 0 {
		db = db.Where("in_warehouse_id = ?", inWarehouseID)
	}
	if outWarehouseID != 0 {
		db = db.Where("out_warehouse_id = ?", outWarehouseID)
	}
	if status != 0 {
		db = db.Where("status = ?", status)
	}
	if err = db.Count(&total).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	err = db.Order("id desc").Offset((pageNo - 1) * pageSize).Limit(pageSize).Find(&orders).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// GetScheduleOrder 获取调拨单
func (d *Dao) GetScheduleOrder(ctx context.Context, sgID uint32, orderNumber string) (order *model.ScheduleOrder, err error) {
	order = &model.ScheduleOrder{}
	err = d.TransContext(ctx).Model(&model.ScheduleOrder{}).Where("sg_id = ? and order_number = ?", sgID, orderNumber).Take(&order).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// FindScheduleOrderDetails 获取调拨单详情
func (d *Dao) FindScheduleOrderDetails(ctx context.Context, orderIDs []uint64) (details []*model.ScheduleDetail, err error) {
	err = d.TransContext(ctx).Model(&model.ScheduleDetail{}).Where("order_id in ?", orderIDs).Find(&details).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}
